<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: modification.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * 'modification' class for the Fusion Registry.
 *
 * @package Fusion Registry
 * @version $Id: modification.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

/**
 * Fusion Registry core require
 */
require_once(REGISTRY_PATH.'/lib/core.php');

/**
 * Class 'registry_modification' is in charge of viewing, adding, modifying modifications of items.
 *
 * This class should be invoked by the parent integration harness.
 * Most functions of this class do not have return values, instead the
 * redirect function is called to print a pretty thank you message to the
 * end user and stops the procedural code.
 *
 * @package Fusion Registry
 */
class registry_modification
{
    var $ipsclass;

    /**#@+ @var string */
    var $output     = "";
    var $page_title = "";
    /**#@-*/

    /**#@+ @var array */
    var $data            = array();
    var $registry_config = array();
    var $nav_bar         = array();
    var $html            = array( 'core', 'mod', 'gallery' );
    var $lib             = array( 'custom_fields', 'functions', 'upload', 'parser' );
    /**#@-*/

    /** @var object registry_core */
    var $core = "";

    /**
     * Invoked from parent harness, this executes the code.
     *
     * This is the only function which should be called from the harness.
     * This function is the traffic cop for this class, it should
     * do very little procedural code, if any.
     *
     * @param string $param Function to call
     */
    function auto_run($param='')
    {
        // Initialize core
        $this->core = new registry_core();
        $this->core->ipsclass =& $this->ipsclass;
        $this->core->auto_run(&$this);

        // Setup parser
        $this->lib['parser']->parse_smilies = $this->registry_config['allow_bbcode_mod'];
        $this->lib['parser']->parse_bbcode  = $this->registry_config['allow_bbcode_mod'];
        $this->lib['parser']->parse_html    = $this->registry_config['allow_html_mod'];
        $this->lib['parser']->parse_nl2br   = 1;

        // Start our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."'>".$this->ipsclass->lang['title']."</a>";

        // Which way to go?
        switch( $param )
        {
            case 'do_delete':
                $this->data['body'] = $this->do_delete();
                break;

            case 'do_modify':
                $this->data['body'] = $this->do_modify();
                break;

            case 'do_new':
                $this->data['body'] = $this->do_new();
                break;

            case 'modify_menu':
                $this->data['body'] = $this->modify_menu();
                break;

            case 'new_menu':
                $this->data['body'] = $this->new_menu();
                break;

            case 'view':
            default:
                $this->data['body'] = $this->view();
                break;
        }

        // Let's create the common output elements now
        $this->data['navigation']     = $this->lib['functions']->do_navigation();
        $this->data['latest_updated'] = $this->lib['functions']->do_latest_updated();
        $this->data['my_cars']        = $this->lib['functions']->do_my_items();

        // Print it all out
        $this->output = $this->core->process_output();

        $this->ipsclass->print->add_output( $this->output );

        // Shall we use our Custom page title, or the default one?
        $this->page_title = empty($this->page_title) ? $this->ipsclass->lang['page_title'] : $this->page_title;

        // Set the title and nav bar, print the output
        $this->ipsclass->print->do_output( array( 'TITLE' => $this->ipsclass->vars['board_name'] .' -> '. $this->page_title,
                                                  'NAV'   => $this->nav_bar ) );
    }


    /**
     * Delete a modification, not undo-able
     *
     * @return string Failure returns template 'message'
     */
    function do_delete()
    {
        // For security measures we are going to make sure that the person
        // logged in is the owner of the mod trying to be deleted.  So first
        // we need to select the vehicle and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT mods.*, images.attach_id, images.attach_hits, images.attach_ext,
                                        images.attach_file, images.attach_location, images.attach_thumb_location
                                     FROM ibf_registry_mods AS mods
                                         LEFT JOIN ibf_registry_images AS images ON images.attach_id = mods.image_id
                                     WHERE mods.id = '" . $this->ipsclass->input['MID'] . "'");

        $mod_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $mod_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this vehicle!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // If they are a 'supmod' and this isn't their item reset the member id
        //   for the rest of this function
        $item_owner_id = $this->ipsclass->member['id'];

        if ( ( $this->ipsclass->member['g_is_supmod'] == 1 ) AND
             ( $this->ipsclass->member['id'] != $mod_data['member_id'] ) )
        {
            $item_owner_id = $mod_data['member_id'];
        }

        // Only try to delete image if it has one
        if (!empty($mod_data['attach_id']))
        {
            // Delete highlight image from DB
            $this->ipsclass->DB->query("DELETE FROM ibf_registry_images WHERE attach_id='". $mod_data['image_id'] ."'" );

            // Delete highlight image from disk
            if (is_file($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_location']);
            }

            // And the thumbnail
            if (is_file($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_thumb_location']))
            {
                @unlink($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_thumb_location']);
            }
        }

        // Well, all looks good, let's go ahead and delete the mod
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_mods WHERE id = '". $this->ipsclass->input['MID'] ."' AND member_id = '" . $item_owner_id . "'");

        // Now we need to update the date_updated of the vehicle entry itself
        $db_string = $this->ipsclass->DB->compile_db_update_string( array('date_updated' => time()) );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '" . $this->ipsclass->input['CID'] . "'");
        unset($db_string);

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['delete_mod_success'], "autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Update a modification in the Fusion Registry
     *
     * @return string Failure returns template 'message'
     */
    function do_modify()
    {
        // For security measures we are going to make sure that the person
        // logged in is the owner of the mod trying to be modified.  So first
        // we need to select the mod and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT m.*, images.attach_id, images.attach_hits, images.attach_ext,
                                        images.attach_file, images.attach_location, images.attach_thumb_location
                                     FROM ibf_registry_mods AS m
                                         LEFT JOIN ibf_registry_images AS images ON images.attach_id = m.image_id
                                     WHERE m.id = '" . $this->ipsclass->input['MID'] . "'");

        $mod_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $mod_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this item!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Let's check up on the image attachment to see if anything is changing
        if ($mod_data['image_id'])
        {
            if ( isset($this->ipsclass->input['editupload']) AND ($this->ipsclass->input['editupload'] != 'keep') )
            {
                if ( ($this->ipsclass->input['editupload'] == 'new') OR
                     ($this->ipsclass->input['editupload'] == 'new_url') )
                {
                    // w00t, we're uploading a new ..um.. upload
                    $sql_image_id = $this->lib['upload']->process_upload('registry_mod',$this->ipsclass->input['MID']);

                    if ( is_int($sql_image_id) && ($this->lib['upload']->error_msg() == "") )
                    {
                        // Update the vehicle entry for this highlight image
                        $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'image_id' => $sql_image_id ) );

                        $this->ipsclass->DB->query("UPDATE ibf_registry_mods SET $db_string WHERE id = '". $this->ipsclass->input['MID'] . "'");
                    }
                }
                else if ($this->ipsclass->input['editupload'] == 'delete')
                {
                    // Simply remove the DB as we've already removed the file
                    $this->ipsclass->DB->query("DELETE FROM ibf_registry_images WHERE attach_id='". $mod_data['image_id'] ."'");

                    // Update the garage entry to remove the image_id column
                    $this->ipsclass->DB->query("UPDATE ibf_registry_mods SET image_id=NULL WHERE id='". $this->ipsclass->input['MID'] . "'");
                }

                if ($this->lib['upload']->error_msg() == "")
                {
                    // We're either uploading a new attachment, or deleting one, so lets
                    // remove the old attachment if we don't have any errors so far
                    if (is_file($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_location']))
                    {
                        @unlink($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_location']);
                    }

                    // And the thumbnail
                    if (is_file($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_thumb_location']))
                    {
                        @unlink($this->ipsclass->vars['upload_dir']."/".$mod_data['attach_thumb_location']);
                    }

                    // Also remove the old entry from the DB
                    $this->ipsclass->DB->query("DELETE FROM ibf_registry_images WHERE attach_id='". $mod_data['image_id'] ."'");
                }
            }
        }
        else
        {
            // Is there a new attachment?

            $sql_image_id = $this->lib['upload']->process_upload('registry_mod',$this->ipsclass->input['MID']);

            if ( is_int($sql_image_id) && ($this->lib['upload']->error_msg() == "") )
            {
                // Update the vehicle entry for this highlight image
                $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'image_id' => $sql_image_id ) );

                $this->ipsclass->DB->query("UPDATE ibf_registry_mods SET $db_string WHERE id = '". $this->ipsclass->input['MID'] . "'");
            }
        }

        // Will be used to store the created and updated time in DB.
        // We are not using mysql's timestamp format because we are
        // control freaks :)
        $epoch_time = time();

        // Make sure commas or dollar signs don't mess up the price
        $this->ipsclass->input['price'] = preg_replace('/(\,|&#036;)/', '', $this->ipsclass->input['price']);
        $this->ipsclass->input['install_price'] = preg_replace('/(\,|&#036;)/', '', $this->ipsclass->input['install_price']);

        // This constructs the FIELD_NAMES and FIELD_VALUES for sql
        $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'category_id'    => $this->ipsclass->input['category'],
                                                                           'title'          => $this->ipsclass->input['title'],
                                                                           'price'          => $this->ipsclass->input['price'],
                                                                           'install_price'  => $this->ipsclass->input['install_price'],
                                                                           'rating'         => $this->ipsclass->input['rating'],
                                                                           'comments'       => $this->lib['parser']->pre_db_parse( $this->ipsclass->input['comments'] ),
                                                                           'date_updated'   => $epoch_time,
                                                                  )      );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_mods SET $db_string WHERE id = '" . $this->ipsclass->input['MID'] . "'");
        unset($db_string);

        // Now we need to update the date_updated of the vehicle entry itself
        $db_string = $this->ipsclass->DB->compile_db_update_string( array('date_updated' => $epoch_time) );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '" . $this->ipsclass->input['CID'] . "'");
        unset($db_string);

        // Do we need a line break?
        $error_text = $this->lib['upload']->error_msg();

        if ( empty($error_text) == FALSE )
        {
        	$error_text = '<br />'. $error_text;
        }

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['modify_mod_success'] . $error_text, "autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Insertion of new modification into registry_mods
     *
     * @return string Failure returns template 'message'
     */
    function do_new()
    {
        // Do they have permission?
        if ( $this->ipsclass->check_perms($this->registry_config['add_perms']) != TRUE )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // For security measures we are going to make sure that the person
        // logged in is the owner of the vehicle trying to be deleted.  So first
        // we need to select the vehicle and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT * FROM ibf_registry_items WHERE id = '" . $this->ipsclass->input['CID'] . "'");
        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this vehicle!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Let's make sure we have a title
        if ( !($this->ipsclass->input['title']) )
        {
            // Sorry bud, we need/require this info :)
            $data = array(
                            message    => $this->ipsclass->lang['no_mod_title_error'],
                            next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=new_mod&amp;CID=". $this->ipsclass->input['CID'],
                            next_title => "{$this->ipsclass->lang['add']} {$this->ipsclass->lang['g_new']} {$this->ipsclass->lang['modification']}",
                         );

            // Return the message
            return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
        }

        // Let's make sure we have a category
        if ( !($this->ipsclass->input['category']) )
        {
            // Sorry bud, we need/require this info :)
            $data = array(
                            message    => $this->ipsclass->lang['no_category_error'],
                            next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=new_mod&amp;CID=". $this->ipsclass->input['CID'],
                            next_title => "{$this->ipsclass->lang['add']} {$this->ipsclass->lang['g_new']} {$this->ipsclass->lang['modification']}",
                         );

            // Return the message
            return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
        }

        // Will be used to store the created and updated time in DB.
        // We are not using mysql's timestamp format because we are
        // control freaks :)
        $epoch_time = time();

        // Make sure commas or dollar signs don't mess up the price
        $this->ipsclass->input['price'] = preg_replace('/(\,|&#036;)/', '', $this->ipsclass->input['price']);
        $this->ipsclass->input['install_price'] = preg_replace('/(\,|&#036;)/', '', $this->ipsclass->input['install_price']);

        // This constructs the FIELD_NAMES and FIELD_VALUES for sql
        $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'member_id'      => $this->ipsclass->member['id'],
                                                                           'category_id'    => $this->ipsclass->input['category'],
                                                                           'item_id'        => $this->ipsclass->input['CID'],
                                                                           'title'          => $this->ipsclass->input['title'],
                                                                           'price'          => $this->ipsclass->input['price'],
                                                                           'install_price'  => $this->ipsclass->input['install_price'],
                                                                           'rating'         => $this->ipsclass->input['rating'],
                                                                           'comments'       => $this->lib['parser']->pre_db_parse( $this->ipsclass->input['comments'] ),
                                                                           'date_created'   => $epoch_time,
                                                                           'date_updated'   => $epoch_time,
                                                                  )      );

        // Execute the sql call
        $this->ipsclass->DB->query("INSERT INTO ibf_registry_mods (" .$db_string['FIELD_NAMES']. ") VALUES (". $db_string['FIELD_VALUES'] .")");
        unset($db_string);

        // Save the sql image id for later use
        $mod_id = $this->ipsclass->DB->get_insert_id();

        // Grab that image, if they have permission!
        if ( $this->ipsclass->check_perms($this->registry_config['upload_perms']) == TRUE )
        {
            $sql_image_id = $this->lib['upload']->process_upload('registry_mod',$mod_id);

            // Record the uploaded image (if any)
            if ( is_int($sql_image_id) && ($this->lib['upload']->error_msg() == "") )
            {
                // Update the vehicle entry for this highlight image
                $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'image_id' => $sql_image_id ) );

                $this->ipsclass->DB->query("UPDATE ibf_registry_mods SET $db_string WHERE id = '$mod_id'");
            }
        }

        // Now we need to update the date_updated of the vehicle entry itself
        $db_string = $this->ipsclass->DB->compile_db_update_string( array('date_updated' => $epoch_time) );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '" . $this->ipsclass->input['CID'] . "'");
        unset($db_string);

        // Do we need a line break?
        $error_text = $this->lib['upload']->error_msg();

        if ( empty($error_text) == FALSE )
        {
        	$error_text = '<br />'. $error_text;
        }

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['new_mod_success'] . $error_text, "autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Build the HTML menu for modifying a modification
     *
     * @return string Success returns template 'modify_menu'; Failure returns template 'message'
     */
    function modify_menu()
    {
        // For security measures we are going to make sure that the person
        // logged in is the owner of the mod trying to be modified.  So first
        // we need to select the mod and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT mods.*, images.attach_hits, images.attach_ext, images.attach_id, images.attach_file
                                     FROM ( ibf_registry_mods AS mods, ibf_registry_items AS g )
                                        LEFT JOIN ibf_registry_images AS images ON images.attach_id = mods.image_id
                                     WHERE mods.id = '" . $this->ipsclass->input['MID'] . "' AND g.id = mods.item_id");

        $mod_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $mod_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this item!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // First let's grab the user's vehicle info
        $cf_entries = $this->lib['custom_fields']->get_cf_entries( array( 'WHERE' => "item_id='".$this->ipsclass->input['CID']."'" ) );

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $data['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $data['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                    'value' => $cf_entries[$cf_field_id]['field_value'],
                                                                                                    'type' => 'form',
                                                                                           )      );
            // Append space for readability
            $data['highlight_field_value'] .= ' ';
        }

        // Un-parse the comments
        $mod_data['comments'] = $this->lib['parser']->pre_edit_parse( $mod_data['comments'] );

        // Build the category select HTML
        $mod_data['categories'] = $this->lib['functions']->build_category_html( array(selected => $mod_data['category_id']) );

        // Build the rating HTML
        $mod_data['rating'] = $this->lib['functions']->build_rating_html( array( START => 10,
                                                                                 END => 1,
                                                                                 selected => $mod_data['rating'],
                                                                        )      );

        // Let's construct the correct image upload fields
        if ( ($this->registry_config['allow_image_upload'] == 1) and
             ($this->registry_config['allow_mod_image'] == 1) and
             ($this->registry_config['max_image_kbytes'] > 0) and
             ($this->ipsclass->check_perms($this->registry_config['upload_perms']) == TRUE) )
        {
            $size_string = $this->ipsclass->size_format( $this->registry_config['max_image_kbytes'] * 1024 );

            if ($mod_data['attach_id'] != "")
            {
                // If they are allowed to use url images, prep the HTML
                // If they have an existing remote image, get the url!
                if ( preg_match( "/^http:\/\//i", $mod_data['attach_id']) )
                {
                    $url_field = $mod_data['attach_id'];
                }
                else
                {
                    $url_field = 'http://';
                }

                if ( $this->registry_config['allow_image_url'] == 1 )
                {
                    $edit_url_field = $this->ipsclass->compiled_templates['skin_registry_mod']->edit_url_field( array( url => $url_field,
                                                                                                                       target_form => 'modify_mod'
                                                                                                              )      );
                }

                // An image attachment exists, show the edit upload form elements
                $mod_data['upload'] = $this->ipsclass->compiled_templates['skin_registry_mod']->edit_upload_field( array( max_size => $size_string,
                                                                                                                          max_resolution => $this->registry_config['max_image_resolution'],
                                                                                                                          file_name => $mod_data['attach_file'],
                                                                                                                          target_form => 'modify_mod',
                                                                                                                          edit_url_field => $edit_url_field
                                                                                                                 )      );
            }
            else
            {
                // No image, do they want to upload a new?
                $mod_data['upload'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_field( $size_string, $this->registry_config['max_image_resolution'] );

                // If they are allowed to use url images, prep the HTML
                if ( $this->registry_config['allow_image_url'] == 1 )
                {
                    $mod_data['upload_url'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_url_field( array( url => 'http://',
                                                                                                                                  target_form => 'modify_mod'
                                                                                                                         )      );
                }
            }
        }

        // Set page title
        $this->page_title = $mod_data['title'];

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}'>{$data['highlight_field_value']}</a>";

        // Wrap it up by returning data
        return $this->ipsclass->compiled_templates['skin_registry_mod']->modify_menu($mod_data);
    }


    /**
     * Build the HTML menu for adding a new modification to a vehicle
     *
     * @return string Success returns template 'add_new_mod_menu'; Failure returns template 'message'
     */
    function new_menu()
    {
        // Do they have permission?
        if ( $this->ipsclass->check_perms($this->registry_config['add_perms']) != TRUE )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Grab the vehicle info
        $this->ipsclass->DB->query("SELECT g.* FROM ibf_registry_items AS g WHERE g.id='". $this->ipsclass->input['CID'] ."'");
        $data = $this->ipsclass->DB->fetch_row();

        // Now let's check to make sure they own this vehicle
        if ( $this->ipsclass->member['id'] != $data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this vehicle!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // First let's grab the user's vehicle info
        $cf_entries = $this->lib['custom_fields']->get_cf_entries( array( 'WHERE' => "item_id='".$this->ipsclass->input['CID']."'" ) );

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $data['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $data['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                    'value' => $cf_entries[$cf_field_id]['field_value'],
                                                                                                    'type' => 'view',
                                                                                           )      );
            // Append space for readability
            $data['highlight_field_value'] .= ' ';
        }

        // Build the category select HTML
        $data['categories'] = $this->lib['functions']->build_category_html();

        // Build the rating HTML
        $data['rating'] = $this->lib['functions']->build_rating_html( array( START => 10,
                                                                             END => 1,
                                                                             selected => 10,
                                                                    )      );

        // If they are allowed to upload images, let's prepare the HTML
        if ( ($this->registry_config['allow_image_upload'] == 1) and
             ($this->registry_config['allow_mod_image'] == 1) and
             ($this->registry_config['max_image_kbytes'] > 0) and
             ($this->ipsclass->check_perms($this->registry_config['upload_perms']) == TRUE) )
        {
            $size_string = $this->ipsclass->size_format( $this->registry_config['max_image_kbytes'] * 1024 );

            $data['upload'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_field( $size_string, $this->registry_config['max_image_resolution'] );

            // If they are allowed to use url images, prep the HTML
            if ( $this->registry_config['allow_image_url'] == 1 ) {
                $data['upload_url'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_url_field( array( url => 'http://',
                                                                                                                          target_form => 'add_new_mod'
                                                                                                                 )      );
            }
        }

        // Set page title
        $this->page_title = $this->ipsclass->lang['add'].' '.$this->ipsclass->lang['modification'];

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}'>{$data['highlight_field_value']}</a>";

        // wOOt, there it is!
        return $this->ipsclass->compiled_templates['skin_registry_mod']->add_new_menu($data);
    }


    /**
     * Build the HTML for viewing a modification
     *
     * @return string Template 'view_mod'
     */
    function view()
    {
        // Do they have permission to browse?
        if ( $this->ipsclass->check_perms($this->registry_config['browse_perms']) != TRUE )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Got attachment types?
        if ( ! is_array( $this->ipsclass->cache['attachtypes'] ) )
        {
            $this->ipsclass->cache['attachtypes'] = array();

            $this->ipsclass->DB->simple_construct( array( 'select' => 'atype_extension,atype_mimetype,atype_post,atype_photo,atype_img', 'from' => 'attachments_type', 'where' => "atype_photo=1 OR atype_post=1" ) );
            $this->ipsclass->DB->simple_exec();

            while ( $r = $this->ipsclass->DB->fetch_row() )
            {
                $this->ipsclass->cache['attachtypes'][ $r['atype_extension'] ] = $r;
            }
        }

        // Query the info we are going to be looking at
        $this->ipsclass->DB->query( "SELECT mods.*, c.title AS cat_title, m.members_display_name, me.avatar_location, me.avatar_size,
                                       images.attach_id, images.attach_hits, images.attach_ext, images.attach_file,
                                       images.attach_thumb_location, images.attach_is_image, images.attach_location,
                                       me.avatar_type, g.id AS garage_id
                                     FROM ( ibf_registry_items AS g, ibf_members AS m, ibf_registry_categories AS c, ibf_registry_mods AS mods )
                                        LEFT JOIN ibf_registry_images AS images ON images.attach_id = mods.image_id
                                        LEFT JOIN ibf_member_extra AS me ON m.id = me.id
                                     WHERE mods.id = '" . $this->ipsclass->input['MID'] . "'
                                       AND g.id = mods.item_id
                                       AND m.id = mods.member_id
                                       AND c.id = mods.category_id");

        $data = $this->ipsclass->DB->fetch_row();

        // Parse the comments 'safely'
        $data['comments'] = $this->lib['parser']->pre_display_parse( $data['comments'] );

        // Make the dates human readable
        $data['date_updated'] = $this->ipsclass->get_date( $data['date_updated'], 'LONG' );
        $data['date_created'] = $this->ipsclass->get_date( $data['date_created'], 'LONG' );

        // Pretty avatar
        $data['avatar'] = $this->ipsclass->get_avatar( $data['avatar_location'], $this->ipsclass->member['view_avs'], $data['avatar_size'], $data['avatar_type'] );

        // Do we have a highlight image?  If so, prep the HTML
        if (empty($data['image_id']) == FALSE)
        {
            if ( $data['attach_is_image'] )
            {
                // Do we have a thumbnail?  If so, our job is simple here :)
                if ( (empty($data['attach_thumb_location']) == FALSE) and
                     ($data['attach_thumb_location'] != $data['attach_location']) and
                     (@file_exists($this->ipsclass->vars['upload_dir']."/".$data['attach_thumb_location'])) )
                {
                    // Form the correct image link if it's remote
                    $image_link = "{$this->ipsclass->vars['upload_url']}/{$data['attach_thumb_location']}";

                    // Yippie, our thumbnail is already made for us :)
                    $data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_real_img_thumb(
                                                    array(  'filename' => $image_link,
                                                            'hits'     => $data['attach_hits'],
                                                            'type'     => 'registry_mod',
                                                            'id'       => $data['id'],
                                                   )      );
                }
                else
                {
                    // Since we don't have a pre-made thumb we are going
                    //   to fall back on the old style :(

                    $img_size = array();

                    // Is this a remote image?
                    if ( ($data['attach_thumb_location'] == "remote") OR preg_match("/^http:\/\//i", $data['attach_location']) )
                    {
                        $img_size = @GetImageSize( $data['attach_location'] );
                    }
                    else
                    {
                        $img_size = @GetImageSize( $this->ipsclass->vars['upload_url']."/".$data['attach_location'] );
                    }

                    // Form the correct image link if it's remote
                    $image_link = ( ($data['attach_thumb_location'] == "remote") OR preg_match("/^http:\/\//i", $data['attach_location']) )
                                ? $data['attach_location']
                                : "{$this->ipsclass->vars['upload_url']}/{$data['attach_location']}";

                    if ( $img_size[0] < 1 )
                    {
                        $img_size    = array();
                        $img_size[0] = $this->registry_config['thumbnail_resolution'] + 1;
                        $img_size[1] = $this->registry_config['thumbnail_resolution'] + 1;
                    }

                    //----------------------------------------------------
                    // Do we need to scale?
                    //----------------------------------------------------

                    if ( ( $img_size[0] <= $this->registry_config['thumbnail_resolution'] ) AND
                         ( $img_size[1] <= $this->registry_config['thumbnail_resolution'] ) )
                    {
                        $data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_img( $image_link );
                    }
                    else
                    {
                        $im = $this->ipsclass->scale_image( array( 'max_width'  => $this->registry_config['thumbnail_resolution'],
                                                                   'max_height' => $this->registry_config['thumbnail_resolution'],
                                                                   'cur_width'  => $img_size[0],
                                                                   'cur_height' => $img_size[1]
                                                          )      );

                        $data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_img_thumb(
                                                        array( 'filename' => $image_link,
                                                               'width'    => $im['img_width'],
                                                               'height'   => $im['img_height'],
                                                               'hits'     => $data['attach_hits'],
                                                               'id'       => $data['id'],
                                                               'type'     => 'registry_mod',
                                                      )      );
                    }
                }
            } // End if image
            else
            {
                // This appears to be a non-image attachment, let's show it!
                $data['highlight_image'] = $this->ipsclass->compiled_templates['skin_registry_core']->show_attachments(
                                                array( 'image' => $this->ipsclass->cache['attachtypes'][ $data['attach_ext'] ]['atype_img'],
                                                       'name'  => $data['attach_file'],
                                                       'id'    => $data['id'],
                                                       'type'  => 'registry_mod',
                                              )      );
            }
        }

        // First let's grab the user's vehicle info
        $cf_entries = $this->lib['custom_fields']->get_cf_entries( array( 'WHERE' => "item_id='".$this->ipsclass->input['CID']."'" ) );

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $data['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $data['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                    'value' => $cf_entries[$cf_field_id]['field_value'],
                                                                                                    'type' => 'view',
                                                                                           )      );
            // Append space for readability
            $data['highlight_field_value'] .= ' ';
        }

        // Grab our nifty popup code
        $data['popup_javascript'] = $this->ipsclass->compiled_templates['skin_registry_core']->popup_javascript();

        // Set page title
        $this->page_title = $data['members_display_name'] ."'s ". $data['highlight_field_value'];

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=view_item&amp;CID={$this->ipsclass->input['CID']}'>{$data['highlight_field_value']}</a>";

        // Wrap it up by returning data
        return $this->ipsclass->compiled_templates['skin_registry_mod']->view($data);
    }
}